package sandbox.dao;

import java.io.Serializable;

import javax.persistence.EntityManager;
import javax.persistence.LockModeType;

/**
 * As its name suggests this class is targeted to JPA and therefore is dependent
 * on an entity manager. However it does not define how the JPA entity manager
 * is obtained.
 *
 * @author roger
 *
 * @param <TYPE>
 * @param <ID>
 */
public abstract class AbstractDAOJPA<TYPE extends Serializable, ID extends Serializable>
    implements GenericDAO<TYPE, ID>
{
	public abstract EntityManager getEntityManager();

	private Class<TYPE> type;

  public AbstractDAOJPA(Class<TYPE> type)
	{
//		Type t = getClass().getGenericSuperclass();
//
//		ParameterizedType pt = (ParameterizedType) t;
//
//		Type[] actualTypeArguments = pt.getActualTypeArguments();
//		
//		if (actualTypeArguments.length == 1)
//		{
//			type = (Class) pt.getActualTypeArguments()[0];
//		}
//		else
//		{
//			throw new IllegalStateException("number of actual type arguments <> 1");
//		}
		this.type = type;
	}

	@Override
	public TYPE findById(ID id, LockModeType lockModeType) throws DAOException
	{
		return (TYPE) getEntityManager().find(type, id, lockModeType);
	}

	@Override
	public TYPE findById(ID id) throws DAOException
	{
		return (TYPE) getEntityManager().find(type, id);
	}

	@Override
	public void persist(TYPE entity) throws DAOException
	{
		getEntityManager().persist(entity);
	}

	@Override
	public TYPE merge(TYPE entity) throws DAOException
	{
		return getEntityManager().merge(entity);
	}

	@Override
	public void delete(ID id) throws DAOException
	{
		getEntityManager().remove(id);
	}

	@Override
	public void flush() throws DAOException
	{
		getEntityManager().flush();
	}

	@Override
	public void clear() throws DAOException
	{
		getEntityManager().clear();
	}
}